from MyUi.Ui_main import *
from MyUi.Ui_udp_trans import *
from MyUi.Ui_ota import *
from MyUi.Ui_hvSet import *
from MyUi.Ui_start import *
from MyUi.Ui_enSet import *
from MyUi.Ui_oneCmd import *
from MyUi.Ui_oneNum import *
from cxpd_can import *
from PyQt5.QtWidgets import QApplication, QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout
from PyQt5.QtCore import Qt


def Nop():
    return

class UdpDialog(QtWidgets.QDialog, Ui_Dialog_udpTrans):
    def __init__(self, parent=None):
        super(UdpDialog, self).__init__(parent)
        self.setupUi(self)

        # 连接按钮的信号到槽函数
        self.pushButton.clicked.connect(self.onPushButtonClicked)

    def onPushButtonClicked(self):
        # 获取输入框的文本
        cmd_ls=[]
        try:
            file_size = int(self.lineEdit_size.text())
            cmd_str = "05110000"+hex(file_size*512)[2:].rjust(8,'0')
            cmd_ls.append(cmd_str)
        except:
            cmd_ls.append("05110000ffffffff")
        start_adress = int(self.lineEdit_start.text())
        cmd_str = "05060000"+hex(start_adress)[2:].rjust(8,'0')
        cmd_ls.append(cmd_str)
        # 执行回调函数
        if self.callback:
            self.callback(cmd_ls)
        # 关闭对话框
        self.close()

    def set_callback(self, callback):
        self.callback = callback

class OtaDialog(QtWidgets.QDialog, Ui_Dialog_Ota):
    def __init__(self, parent=None):
        super(OtaDialog, self).__init__(parent)
        self.setupUi(self)
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore

    def accept_func(self):
        try:
            s="".join(filter(lambda s:s in'0123456789', self.lineEdit.text()))
            size=int(s)
            ip=self.comboBox.currentIndex()
        except:
            self.close()
            return False
        if(ip==0):
            cmd_str="05fe0000"+hex(size)[2:].rjust(8,'0')
        elif(ip==1):
            cmd_str="05fe1100"+hex(size)[2:].rjust(8,'0')
        # self.callback(["050a555555555555","050a555555555555",cmd_str])
        self.callback([cmd_str])
        self.close()

    def reject_func(self):
        self.close()
        
    def set_callback(self, callback):
        self.callback = callback

class hvSetDialog(QtWidgets.QDialog, Ui_Dialog_hvSet):
    def __init__(self,parent=None,last_set:list=[0,0,0],mod_max_voltage=6000,mod_max_current=200):
        super(hvSetDialog, self).__init__(parent)
        self.setupUi(self)
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore
        self.spinBox_hvSetV.setValue(last_set[0])
        self.doubleSpinBox.setValue(last_set[1])
        self.comboBox.setCurrentIndex(last_set[2])
        self.mod_max_voltage=mod_max_voltage
        self.mod_max_current=mod_max_current
        self.last_set=last_set

    def accept_func(self):
        voltage=self.spinBox_hvSetV.value()
        current=self.doubleSpinBox.value()
        hv_switch=self.comboBox.currentIndex()
        print(f"hv_v:{voltage} V,hv_i:{current} uA")
        cmd_ls=[]
        if(hv_switch==0):
            cmd_ls.append("05a1a1000000000a")
            vol_code=(voltage/self.mod_max_voltage)*4096
            cur_code=((current/self.mod_max_current)/5)*4096
            cmd_vset="05a1010000000"+hex(int(vol_code))[2:].rjust(3,'0')
            cmd_iset="05a1020000000"+hex(int(cur_code))[2:].rjust(3,'0')
            cmd_ls.append(cmd_vset)
            cmd_ls.append(cmd_iset)
        elif(hv_switch==1):
            cmd_ls.append("05a1a100000000a0")
            vol_code=(voltage/self.mod_max_voltage)*4096
            cur_code=((current/self.mod_max_current)/5)*4096
            cmd_vset="05a1010000000"+hex(int(vol_code))[2:].rjust(3,'0')
            cmd_iset="05a1020000000"+hex(int(cur_code))[2:].rjust(3,'0')
            cmd_ls.append(cmd_vset)
            cmd_ls.append(cmd_iset)
        elif(hv_switch==2):
            cmd_ls.append("05a1a10000000000")
        self.last_set=[voltage,current,hv_switch]
        self.callback(cmd_ls)
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback):
        self.callback = callback


class startSetDialog(QtWidgets.QDialog, Ui_Dialog_start):
    def __init__(self,parent=None,set_dict:dict={}):
        super(startSetDialog, self).__init__(parent)
        self.setupUi(self)
        self.tableWidget.setRowCount(len(set_dict))
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setHorizontalHeaderLabels(["Item", "Value"])
        self.tableWidget.setColumnWidth(0, 150)  # 第一列宽150
        self.tableWidget.setColumnWidth(1, 120)
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore
        row = 0
        for key, value in set_dict.items():
            key_item = QTableWidgetItem(key)
            value_item = QTableWidgetItem(str(value[1]))
            # 禁止第一列的编辑
            key_item.setFlags(key_item.flags() & ~Qt.ItemIsEditable)
            self.tableWidget.setItem(row, 0, key_item)
            self.tableWidget.setItem(row, 1, value_item)
            row += 1

    def accept_func(self):# 获取行数
        rows = self.tableWidget.rowCount()
        # 遍历每一行
        # try:
        cmd_ls=[]
        for row in range(rows):
            # 获取每行的键和值
            key_item = self.tableWidget.item(row, 0)
            value_item = self.tableWidget.item(row, 1)
            if key_item and value_item:
                key = key_item.text()
                value = value_item.text()
                cmd_str=self.cmd(key,value)
                cmd_ls.append(cmd_str)
        cmd_pre=self.accept_precmd()
        try:
            if(isinstance(cmd_pre[0],str) and cmd_pre[0][0:2]=='05'):
                self.callback(cmd_pre)
        except:
            pass
        self.callback(cmd_ls)
    # except:
        #     print("输入值有错")
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback, cmd_gen_func,accept_precmd=Nop):
        self.callback = callback
        self.cmd=cmd_gen_func
        self.accept_precmd=accept_precmd

class startSetDialog_withParam(QtWidgets.QDialog, Ui_Dialog_start):
    def __init__(self,parent=None,set_dict:dict={}):
        super(startSetDialog_withParam, self).__init__(parent)
        self.setupUi(self)
        self.tableWidget.setRowCount(len(set_dict))
        self.tableWidget.setColumnCount(2)
        self.tableWidget.setHorizontalHeaderLabels(["Item", "Value"])
        self.tableWidget.setColumnWidth(0, 150)  # 第一列宽150
        self.tableWidget.setColumnWidth(1, 120)
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore
        row = 0
        for key, value in set_dict.items():
            key_item = QTableWidgetItem(key)
            value_item = QTableWidgetItem(str(value[1]))
            # 禁止第一列的编辑
            key_item.setFlags(key_item.flags() & ~Qt.ItemIsEditable)
            self.tableWidget.setItem(row, 0, key_item)
            self.tableWidget.setItem(row, 1, value_item)
            row += 1

    def accept_func(self):# 获取行数
        rows = self.tableWidget.rowCount()
        # 遍历每一行
        # try:
        cmd_ls=[]
        for row in range(rows):
            # 获取每行的键和值
            key_item = self.tableWidget.item(row, 0)
            value_item = self.tableWidget.item(row, 1)
            if key_item and value_item:
                key = key_item.text()
                value = value_item.text()
                cmd_str=self.cmd(key,value,self.append_param)
                cmd_ls.append(cmd_str)
        cmd_pre=self.accept_precmd()
        try:
            if(isinstance(cmd_pre[0],str) and cmd_pre[0][0:2]=='05'):
                self.callback(cmd_pre)
        except:
            pass
        self.callback(cmd_ls)
    # except:
        #     print("输入值有错")
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback, cmd_gen_func,accept_precmd=Nop,append_param=None):
        self.callback = callback
        self.cmd=cmd_gen_func
        self.accept_precmd=accept_precmd
        self.append_param=append_param


class enSetDialog(QtWidgets.QDialog, Ui_Dialog_enSet):
    def __init__(self,parent=None,sel_cmd=['0000000000000000']*2):
        super(enSetDialog, self).__init__(parent)
        self.setupUi(self)
        self.sel_cmd=sel_cmd
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore

    def accept_func(self):# 获取行数
        sel_set=self.comboBox.currentIndex()
        cmd_ls=[]
        cmd_ls.append(self.sel_cmd[sel_set])
        self.callback(cmd_ls)
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback):
        self.callback = callback

class oneCmdDialog(QtWidgets.QDialog, Ui_Dialog_oneCmd):
    def __init__(self,parent=None,sel_cmd=['0000000000000000']):
        super(oneCmdDialog, self).__init__(parent)
        self.setupUi(self)
        self.sel_cmd=sel_cmd
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore

    def accept_func(self):# 获取行数
        self.callback(self.sel_cmd)
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback):
        self.callback = callback

class oneNumDialog(QtWidgets.QDialog, Ui_Dialog_oneNum):
    def __init__(self,parent=None,cmd_front:str="00000000"):
        super(oneNumDialog, self).__init__(parent)
        self.setupUi(self)
        self.cmd_front=cmd_front
        self.buttonBox.accepted.connect(self.accept_func) # type: ignore
        self.buttonBox.rejected.connect(self.reject_func) # type: ignore

    def accept_func(self):
        num_str=self.lineEdit.text()
        num=try_trans_uint(num_str)
        cmd_str=self.cmd_front+hex(num)[2:].rjust(8,'0')
        self.callback([cmd_str])
        self.close()

    def reject_func(self):
        self.close()

    def set_callback(self, callback):
        self.callback = callback